<template>
  <div :style="{ '--theme': $store.getters.themeColor }">
    <div class="header">
      <div
        :class="['btn', prevBtnDisabled || tableIfShow ? 'disabled' : '']"
        @click="prevEvent"
      >
        <span
          style="margin-right: 6px; font-size: 12px"
          class="iconfont icon-PC_icon_shangyishijian"
        ></span>
        上一事件
      </div>
      <div class="btn">
        <el-button
          v-if="
            !isDisabled() &&
            orderData.isHandleDisplay === '1' &&
            !isRecycleBinDetail
          "
          type="danger"
          size="mini"
          plain
          class="supervision-btn"
          @click="showSupervisionDetail"
          >督办</el-button
        >
        <el-button
          class="fs-14 mr-10 down-file common-button"
          type="text"
          @click.stop="downAlarmFile"
          v-hasPermi="['export:alarm:file']"
          :disabled="fileLoading"
          v-if="showDowmAlarmFile"
        >
          <i class="fs-14 pt-2 iconfont icon-daochu"></i>
          <i class="ml-5">导出告警文件</i>
          <i v-show="fileLoading" class="ml-5 el-icon-loading"></i>
        </el-button>
        <el-button
          style="height: 100%"
          class="fs-14 mr-10 down-img common-button"
          type="text"
          v-if="showDownVideo"
          v-hasPermi="['event:alarm:downVideo']"
          @click.stop="downAlarmVideo"
          :disabled="videoLoading"
        >
          <span
            style="margin-right: 4px"
            class="icon-pc_icon_xiazaigaojingshipin iconfont fs-12 mt-1"
          ></span>
          <span>下载告警视频</span>
          <i v-show="videoLoading" class="ml-5 el-icon-loading"></i>
        </el-button>
        <el-button
          v-if="isShowDown()"
          style="height: 100%"
          class="down-img fs-14 common-button"
          title="下载告警图片"
          v-hasPermi="['event:details:downImg']"
          type="text"
          :disabled="imgLoading"
          @click.stop="downAlarmImg"
        >
          <span
            style="margin-right: 4px"
            class="icon-pc_icon_xiazaigaojingtupian iconfont fs-12 mt-1"
          ></span>
          <span>下载告警图片</span>
          <i v-show="imgLoading" class="ml-5 el-icon-loading"></i>
        </el-button>
        <el-button
          style="height: 100%"
          v-hasPermi="['event:details:share']"
          type="text"
          v-if="makeIfShow()"
          class="fs-14 mr-10 down-img common-button"
          @click.stop="jumpWaringOrderId(orderData.warningOrderId)"
        >
          <i
            class="iconfont icon-pc_icon_fenxiang mt-1"
            style="margin-right: 4px; font-size: 12px"
          ></i>
          <span>分享 </span>
        </el-button>
        <el-button
          style="
            height: 100%;
            display: flex;
            line-height: 48px;
            padding: 0;
            margin-right: 4px;
          "
          v-hasPermi="['event:details:collect']"
          v-if="!hideCollectBtn"
          type="text"
          class="fs-14 mr-10 common-button"
          @click.stop="
            changeCollectStatus(
              orderData.warningOrderId,
              orderData.alarmTime,
              orderData.isCollection
            )
          "
        >
          <span
            style="font-size: 12px"
            :class="
              orderData.isCollection === '1'
                ? 'iconfont icon-pc_icon_yishoucang'
                : 'iconfont icon-pc_icon_shoucang'
            "
            :style="orderData.isCollection === '1' ? 'color: #FF6A6C' : ''"
          ></span>
          <span> {{ orderData.isCollection === "1" ? "已收藏" : "收藏" }}</span>
        </el-button>
        <el-divider direction="vertical" style="padding: 0px 12px"></el-divider>
        <div
          :class="['btn', nextBtnDisabled || tableIfShow ? 'disabled' : '']"
          @click="nextEvent"
        >
          <span style="margin-left: 4px">下一事件</span>
          <span
            style="margin-left: 6px; font-size: 12px"
            class="iconfont icon-PC_icon_xiayishijian"
          ></span>
        </div>
      </div>
    </div>
    <hr class="custom-hr" />
    <el-dialog
      title="分享"
      :visible.sync="shareOpen"
      class="label-config-dialog"
      width="550px"
      @close="removeShare()"
      :close-on-click-modal="false"
    >
      <div style="padding: 0 20px">
        <div class="title">
          <div class="label">【中国铁塔】{{ orderData.alarmBody }}</div>
          <div class="value">{{ urlShare }}</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="fs-14" @click="handelCopyLink('PC')"
          >复制到PC端</el-button
        >
        <el-button type="primary" class="fs-14" @click="handelCopyLink('APP')"
          >复制到移动端</el-button
        >
        <el-button class="fs-14" @click="removeShare()">取消</el-button>
      </div>
    </el-dialog>
    <SupervisionDetail
      :visible.sync="supervisionDetail"
      :orderData="orderData"
    ></SupervisionDetail>
  </div>
</template>
<script>
import { getQueryString } from "@/utils/common";
import { queryFlowLink } from "@/api/modules/eventManagement/eventDialog/trueWarnDialog";
import { getFlow } from "@/api/modules/eventManagement/getFlowId";
import {
  addWarningOrderCollection,
  delWarningOrderCollection,
} from "@/api/modules/eventManagement/eventDetail";
import {
  getOrderList,
  downLoadZipPost,
} from "@/api/modules/eventManagement/eventManagement";
import { qryWarningOrderCollection } from "@/api/modules/eventManagement/myFavorites/view";
import { getInterceptList } from "@/api/modules/eventManagement/recycleBin";
import { getLeaderAuditList } from "@/api/modules/eventManagement/leadDirection/leadDirectionList";
import { getOrderListForOperate } from "@/api/system/custom.js";
import { getAPPShareUrl, jumpWaringOrderIdCom } from "./common/share.js";
import html2canvas from "html2canvas";
import eventBus from "@/utils/event-bus";
import SupervisionDetail from "@/views/pages/eventManagement/eventDialog/SupervisionDetail.vue";
export default {
  name: "eventProcess",
  props: {
    getOrderInfo: {
      type: Function,
      default: () => ({}),
    },
    isDetail: {
      type: Boolean,
      default: false,
    },
    configParam: {
      type: String,
      default: "orderId",
    },
    hideCollectBtn: {
      type: Boolean,
      default: false,
    },
    sourceLink: {
      type: String,
      default: "",
    },
    isAlarmSuppress: {
      type: String,
      default: null,
    },
    localFlag: String,
    maskLoading: {
      type: Boolean,
      default: false,
    },
  },
  inject: {
    orderIdValue: {
      default: () => "",
    },
    orderStatusValue: {
      default: () => "",
    },
    listValue: {
      default: () => [],
    },
    searchParamsValue: {
      type: Function,
      default: () => "",
    },
    pageTypeValue: {
      type: String,
      default: "",
    },
  },
  components: {
    SupervisionDetail,
  },
  data() {
    return {
      tableIfShow: location.href.includes("jumpShare") ? true : false,
      currentLink: "", // 1-研判；2-调度；4-处置；5-核实；6-完结
      warningOrderId: "",
      auditId: "", // 领导批示页面的唯一标识
      orderData: {},
      reldeviceData: {},
      orderDetail: {},
      videoData: {},
      longitude: "", //经度
      latitude: "", //维度
      imgsList: [],
      list: [],
      total: 0,
      prevBtnDisabled: false,
      nextBtnDisabled: false,
      searchParams: {},
      pageType: "",
      loading: false,
      monitors: {},
      reldevice: {},
      urlShare: "",
      shareOpen: false,
      videoLoading: false,
      imgLoading: false,
      fileLoading: false,
      mapDom: null,
      supervisionDetail: false,
      shareId: "", // 分享的短链接
    };
  },
  computed: {
    exportView() {
      return this.isDisabled() ? "1" : "2";
    },
    collectAble() {
      // 可收藏能力
      return this.$store.getters.userInfo.userType === "2";
    },
    getList() {
      if (this.pageType === "eventManagement" || this.pageType === "myEvent") {
        // 事件查询，我的事件-我的待办，我的事件-我的已办
        return getOrderList;
      } else if (this.pageType === "myFavorites") {
        // 我的事件-我的收藏
        return qryWarningOrderCollection;
      } else if (this.pageType === "leadDirection") {
        // 领导批示
        return getLeaderAuditList;
      } else if (this.pageType === "recycleBin") {
        // 回收站
        if (this.isAlarmSuppress) {
          return this.isAlarmSuppress == "1" ? getInterceptList : getOrderList;
        }
        return getInterceptList;
      } else if (this.pageType === "custOperate") {
        // 运营研判
        return getOrderListForOperate;
      } else {
        return false;
      }
    },
    isYanPan() {
      return location.href.includes("custOperateDetail");
    },
    isRecycleBinDetail() {
      return location.href.includes("recycleBinDetail");
    },
    showDownVideo() {
      return (
        (location.href.includes("eventLinks") &&
          !getQueryString("fromLeader")) ||
        location.href.includes("custOperateDetail") ||
        location.href.includes("recycleBinDetail")
      );
    },
    exportSource() {
      // 优化代码
      const href = location.href;
      const page = getQueryString("page");
      if (
        href.includes("eventLinks") ||
        (href.includes("recycleBinDetail") && (page === "12" || page === "13"))
      ) {
        return "1";
      }
      // 原代码验证后可以删除
      // if(location.href.includes('eventLinks') || //事件详情
      //   (location.href.includes('recycleBinDetail') && getQueryString('page') === '12') ||  // 删除告警
      //   (location.href.includes('recycleBinDetail') && getQueryString('page') === '13')) { // 转移告警
      //   return '1'
      // }
      if (
        location.href.includes("recycleBinDetail") &&
        getQueryString("page") === "11"
      ) {
        // 告警压制
        return "2";
      }
      if (location.href.includes("custOperateDetail")) {
        return "3";
      }
    },
    showDowmAlarmFile() {
      return (
        location.href.includes("eventLinks") ||
        location.href.includes("recycleBinDetail")
      );
    },
  },
  watch: {
    warningOrderId(val) {
      this.$emit("update:warningOrderId", val);
    },
    currentLink(val) {
      this.$emit("update:orderStatus", val);
    },
    loading(val) {
      this.$emit("update:maskLoading", val);
    },
  },
  mounted() {
    setTimeout(async () => {
      await this.loadInit();
    });
    eventBus.$on("click-footer-map", this.moveMapDom);
    eventBus.$on("move-map-to-other-view", this.setMapElement);
    eventBus.$on("reloadOrderData", this.getCurEventInfo);
  },
  beforeDestroy() {
    eventBus.$off("reloadOrderData", this.getCurEventInfo);
  },
  methods: {
    async loadInit() {
      let url = location + "";
      if (url.indexOf("?") != -1) {
        this.fromLeader = getQueryString("fromLeader");
        this.pageType = getQueryString("fromPageType");
        if (this.fromLeader === "true") {
          // 领导批示详情
          this.auditId = getQueryString("auditId");
        }
        this.warningOrderId = getQueryString("orderId");
        this.currentLink = getQueryString("orderStatus");
        this.list = JSON.parse(getQueryString("list")) || [];
        this.searchParams = JSON.parse(getQueryString("searchParams"));
      }
      if (this.orderIdValue) {
        // iframe 弹框嵌入 或者 弹框
        this.pageType = this.pageTypeValue;
        this.warningOrderId = this.orderIdValue();
        this.currentLink = this.orderStatusValue();
        this.list = this.listValue() || [];
        this.searchParams = this.searchParamsValue && this.searchParamsValue();
      }
      this.total = this.list.length;
      this.searchParams = this.searchParams || {
        pageNum: 1,
        pageSize: this.total,
      };
      if (sessionStorage.getItem("orderList")) {
        this.list = JSON.parse(sessionStorage.getItem("orderList"));
        this.total = sessionStorage.getItem("orderListTotal");
        sessionStorage.removeItem("orderList");
        sessionStorage.removeItem("orderListTotal");
      }
      // sonar问题修改不能连续超过3个条件运算符，所以拆开
      const shouldGetList = this.getList && !this.list.length && !this.total;
      const isNotSystemMsg = this.sourceLink !== "/system/msg";
      const isTableHidden = !this.tableIfShow;
      if (shouldGetList && isNotSystemMsg && isTableHidden) {
        await this.getListData();
      }
      // 原代码验证后可删除
      // if (this.getList && !this.list.length && !this.total && this.sourceLink !== '/system/msg' && !this.tableIfShow) {
      //   await this.getListData()
      // }
      this.getCurEventInfo();
    },
    async getListData() {
      this.prevBtnDisabled = this.nextBtnDisabled = true;
      const res = await this.getList(this.searchParams);
      this.prevBtnDisabled = this.nextBtnDisabled = false;
      if (res.code === 200) {
        this.list = res.rows || res.data?.rows || 0;
        this.total = res.total || res.data?.total || 0;
      }
    },
    getCurEventInfo() {
      const index = this.getCurIndex();
      if (index === 0 && this.searchParams.pageNum === 1) {
        this.prevBtnDisabled = true;
      } else {
        this.prevBtnDisabled = false;
      }
      const lastPage =
        this.searchParams.pageNum ===
        Math.ceil(this.total / this.searchParams.pageSize);
      if (index === this.list.length - 1 && lastPage) {
        this.nextBtnDisabled = true;
      } else {
        this.nextBtnDisabled = false;
      }
      if (index === -1) {
        this.prevBtnDisabled = true;
        this.nextBtnDisabled = true;
      }
      this.getDetails({
        [this.configParam]: this.warningOrderId,
        orderStatus: this.currentLink,
      });
    },
    // 查询
    getDetails(params) {
      let _this = this;
      _this.loading = true;
      const { localFlag } = this.$route.query;
      if (localFlag) {
        params.localFlag = localFlag;
      }
      //订单信息
      this.getOrderInfo(params)
        .then((resp) => {
          if (resp && resp.code == 200) {
            this.setOrderInfo(resp);
          } else {
            $message.warning(resp.mess);
          }
          _this.loading = false;
        })
        .catch((e) => {
          this.loading = false;
          this.prevBtnDisabled = this.nextBtnDisabled = false;
        });
    },
    setOrderInfo(resp) {
      let _this = this;
      const result = (resp.data.rows && resp.data.rows[0]) || resp.data;
      _this.orderData = result.order;
      if (!_this.orderData.warningOrderId) {
        _this.orderData.warningOrderId = _this.orderData.orderId;
      }
      let msgId = {
        id: result.order.warningOrderId,
        status: result.order.orderStatus,
      };
      this.$store.dispatch("closeSocketMsg", msgId);
      _this.videoData = result.video;
      _this.imgsList = result.imgs;
      if (resp.data.satelliteDeviceList) {
        this.orderData.satelliteDeviceList = resp.data.satelliteDeviceList;
      }
      _this.reldevice =
        _this.videoData === undefined ? {} : _this.videoData.reldevice;
      _this.monitors =
        _this.videoData === undefined
          ? result.monitors
          : _this.videoData.monitors;

      _this.positionMonitor = [
        _this.orderData.latitude,
        _this.orderData.longitude,
      ];
      // _this.longitude=_this.orderData.longitude?_this.orderData.longitude:_this.orderData.deviceLongitude
      // _this.longitude=_this.orderData.latitude?_this.orderData.latitude:_this.orderData.deviceLatitude
      _this.longitude = _this.orderData.longitude;
      _this.latitude = _this.orderData.latitude;
      _this.orderDetail = result.orderDetail || {};
      _this.orderDetail.tenantId = result.order.tenantId;
      // _this.orderDetail.longitude=result.order.longitude
      // _this.orderDetail.latitude=result.order.latitude
      _this.orderDetail.tenantName = result.order.tenantName;
      _this.orderDetail.appVerCode = result.order.appVerCode;
      _this.orderDetail.industryName = result.order.industryName;
      _this.orderDetail.ptzTransP = result.order.ptzTransP;
      _this.orderDetail.ptzTransT = result.order.ptzTransT;
      _this.orderDetail.ptzTransZ = result.order.ptzTransZ;
      _this.orderDetail.alarmFlowName = "";
      if (result.order.alarmFlowName) {
        _this.orderDetail.alarmFlowName = result.order.alarmFlowName;
      }
      this.$emit("update:reldeviceData", result.reldevice);
      console.log(_this.videoData, "_this.videoData");
      this.$emit("update:videoData", _this.videoData);
      this.$emit("update:imgsList", _this.imgsList);
      this.$emit("update:orderDetail", _this.orderDetail);
      this.$emit("update:reldevice", _this.reldevice);
      // this.$emit('update:longitude',  _this.longitude);
      // this.$emit('update:latitude',_this.latitud);
      this.$emit("update:monitors", _this.monitors);
      this.$emit("update:positionMonitor", _this.positionMonitor);
      setTimeout(() => {
        const dom = document.querySelector(
          ".medias-map-component .event_map_big"
        );
        this.mapDom = dom;
        this.moveMapDom();
      }, 1000);
      if (this.isDetail) {
        if (result.satelliteDevice) {
          _this.orderData.satelliteDevice = result.satelliteDevice;
        }
        this.$emit("update:orderData", _this.orderData);
        return;
      }
      if (!_this.orderData.flowId) {
        _this.getFlowIds(
          resp.data.rows[0].order.tenantId,
          resp.data.rows[0].order.warningSource,
          resp.data.rows[0].order.warningTypeId
        );
      } else {
        _this.getFlowAttr();
      }
    },
    getFlowIds(tenantId, warningSource, alarmCode) {
      const _this = this;
      getFlow({
        tenantId: tenantId,
        warningSource: warningSource,
        alarmCode: alarmCode,
      }).then((resp) => {
        if (resp.code == 200) {
          let flowFlow = tenantId + "_" + warningSource;
          _this.orderData.flowId = resp.data[flowFlow];
          _this.getFlowAttr();
        } else {
          console.log("");
        }
      });
    },
    getFlowAttr() {
      queryFlowLink({
        flowId: this.orderData.flowId,
        linkId: this.orderData.linkId,
        warningSource: this.orderData.warningSource,
        templateId: this.orderData.flowTemplate,
      }).then((res) => {
        if (res.code === 200) {
          const result = res.data[0] || {};
          this.orderData.leaderFlag = result.leaderFlag;
          // rollbackFlag 1-可回退 0不可回退
          this.orderData.rollbackFlag =
            result.rollbackFlag === "1" &&
            result.preLink &&
            result.preLink !== "7"
              ? "1"
              : "0";
          this.orderData.signFlag = result.signFlag;
          this.orderData.msgNotifyType = result.msgNotifyType;
          // turnFlag  1-可转派   0-不可转派
          this.orderData.turnFlag = result.turnFlag;
          this.$emit("update:orderData", this.orderData);
        }
      });
    },
    /**
     * 上一事件
     */
    async prevEvent() {
      this.loading = true;
      const index = this.getCurIndex();
      let prevData;
      if ((index === 0 && this.searchParams.pageNum === 1) || index === -1) {
        this.loading = false;
        return null;
      } else if (index === 0 && this.getList) {
        this.searchParams.pageNum -= 1;
        await this.getListData();
        prevData = this.list[this.list.length - 1];
      } else {
        prevData = this.list[index - 1];
      }
      if (prevData) {
        this.warningOrderId = prevData.orderId || prevData.warningOrderId;
        this.currentLink = prevData.orderStatus;
        if (this.fromLeader === "true") {
          this.auditId = prevData.auditId;
        }
        this.saveReadStatus(this.warningOrderId);
        this.getCurEventInfo();
      } else {
        this.loading = false;
      }
    },
    /**
     * 下一事件
     */
    async nextEvent() {
      this.loading = true;
      const index = this.getCurIndex();
      let nextData;
      const lastPage =
        this.searchParams.pageNum ===
        Math.ceil(this.total / this.searchParams.pageSize);
      //
      if ((index === this.list.length - 1 && lastPage) || index === -1) {
        this.loading = false;
        return null;
      } else if (index === this.list.length - 1 && this.getList) {
        this.searchParams.pageNum += 1;
        await this.getListData();
        nextData = this.list[0];
      } else {
        nextData = this.list[index + 1];
      }
      if (nextData) {
        this.warningOrderId = nextData.orderId || nextData.warningOrderId;
        this.currentLink = nextData.orderStatus;
        if (this.fromLeader === "true") {
          this.auditId = nextData.auditId;
        }
        this.saveReadStatus(this.warningOrderId);
        this.getCurEventInfo();
      } else {
        this.loading = false;
      }
    },
    /**
     * 获取当前数据在表格中处于的index
     */
    getCurIndex() {
      if (this.fromLeader === "true") {
        //领导批示页面
        return this.list?.findIndex(
          (ele) => `${ele.auditId}` === `${this.auditId}`
        );
      } else {
        return this.list?.findIndex(
          (ele) =>
            `${ele.orderId}` === `${this.warningOrderId}` ||
            `${ele.warningOrderId}` === `${this.warningOrderId}`
        );
      }
    },
    /**
     * 复制链接
     */
    async handelCopyLink(val) {
      let that = this;
      const titleText = "【中国铁塔】" + that.orderData.alarmBody + "\n";
      let copyDoc = titleText + that.urlShare;
      if (val == "PC") {
        copyDoc = that.urlShare;
      }
      if (val === "APP") {
        let url = await getAPPShareUrl(this.shareId);
        copyDoc = titleText + url;
        console.log(copyDoc, "copyDoc");
      }
      this.$copyText(copyDoc).then(
        (e) => {
          $message.success("链接已复制");
        },
        (e) => {
          $message.success("链接未复制");
        }
      );
    },
    /**
     * 判断在哪个界面
     */
    makeIfShow() {
      if (
        location.href.includes("eventLinks") &&
        !getQueryString("fromLeader")
      ) {
        return true;
      } else {
        return false;
      }
    },
    /**
     * 判断是否是事件详情界面而不是运营研判详情
     */
    isShowDown() {
      return (
        location.href.includes("eventLinks") ||
        location.href.includes("recycleBinDetail") ||
        location.href.includes("custOperateDetail")
      );
    },
    /**
     * 生成分享链接
     */
    async jumpWaringOrderId(warningOrderId) {
      let shareData = await jumpWaringOrderIdCom(warningOrderId);
      this.urlShare = shareData.urlShare;
      this.shareId = shareData.shareId;
      this.shareOpen = this.urlShare ? true : false;
    },
    //关闭弹框
    removeShare() {
      const _this = this;
      _this.urlShare = "";
      this.shareId = "";
      _this.shareOpen = false;
    },
    //收藏
    changeCollectStatus(warningOrderId, alarmTime, isCollection) {
      const _this = this;
      if (isCollection === "0") {
        addWarningOrderCollection({
          warningOrderId,
          alarmTime,
        }).then((res) => {
          if (res.code === 200) {
            $message.success("收藏成功");
            _this.$data.orderData.isCollection = "1";
            //_this.$emit('getViewDataSource');
          } else {
            $message.warning(res.msg);
          }
        });
      } else {
        delWarningOrderCollection({
          warningOrderId,
        }).then((res) => {
          if (res.code === 200) {
            $message.success("取消收藏成功");
            _this.$data.orderData.isCollection = "0";
            //_this.$emit('getViewDataSource');
          } else {
            $message.warning(res.msg);
          }
        });
      }
    },
    /**
     * 下载告警图片
     */
    downAlarmImg() {
      let params = {};
      params.downLoadType = "0";
      params.warningOrderIds = [this.orderData.warningOrderId];
      let fileName = "告警图片下载";
      let url = "";
      if (this.$store.getters.userInfo.tenantId) {
        url = "/export/alarm/order/downloadImgs";
      } else {
        url = "/export/alarm/order/downLoadImgsTower";
        params.name = "中国铁塔"; // 铁塔视角固定值
      }
      if (location.href.includes("eventLinks")) {
        params.orderIdDownLoadType = "1"; // 其他事件下载查询工单表，标识为1
        if (getQueryString("fromPageType") === "myFavorites") {
          params.orderIdDownLoadType = "3"; // 我的收藏详情
        }
      }
      if (location.href.includes("recycleBinDetail")) {
        if (this.$route.query.page == "11") {
          params.orderIdDownLoadType = "2"; // 回收站标识为2
        } else {
          params.orderIdDownLoadType = "1";
        }
      }
      if (location.href.includes("custOperateDetail")) {
        params.orderIdDownLoadType = "4";
      }
      if (this.$route.query.localFlag === "1") {
        params.orderIdDownLoadType = "5";
      }
      this.imgLoading = true;
      downLoadZipPost(url, fileName, params, this.dowImgsCallback);
    },
    // 保存已读状态
    saveReadStatus(orderId) {
      if (this.isYanPan) {
        let id = orderId;
        let userName = this.$store.getters.userInfo.userName;
        let key = userName + "-" + id;
        let savedObj = JSON.parse(localStorage.getItem("userReadStatus"));
        if (savedObj) {
          savedObj[key] = true;
        } else {
          let o = {};
          o[key] = true;
          savedObj = o;
        }
        localStorage.setItem("userReadStatus", JSON.stringify(savedObj));
      }
    },
    downAlarmVideo() {
      let params = {
        warningOrderId: this.orderData.warningOrderId,
        videoUrls: this.videoData.videoList
          ? this.videoData.videoList.map((item) => item.src)
          : this.orderData?.videoUrl?.split(","),
      };
      if (!params.videoUrls.length) {
        return $message.warning("当前告警没有告警视频。");
      }
      let url = "/export/alarm/order/downloadVideos";
      let fileName = "告警视频下载";
      if (!this.$store.getters.userInfo.tenantId) {
        params.name = "中国铁塔";
      }
      this.videoLoading = true;
      downLoadZipPost(url, fileName, params, this.downVideoCallback);
    },
    downVideoCallback(flag) {
      this.videoLoading = false;
      if (flag) {
        $message.success("下载告警视频成功");
      } else {
        $message.error("下载告警视频失败");
      }
    },
    dowImgsCallback(flag) {
      this.imgLoading = false;
      if (flag) {
        $message.success("下载告警图片成功");
      } else {
        $message.error("下载告警图片失败");
      }
    },
    /**
     * 把dom转为图片以blob对象输出
     * @param element dom
     * @returns {Promise}
     */
    htmlElementToBolb(element) {
      return new Promise((resolve, reject) => {
        html2canvas(element)
          .then((canvas) => {
            canvas.toBlob((blob) => {
              // Blob 对象已经准备好
              resolve({
                status: true,
                blob,
              });
            }, "image/jpg"); // 第二个参数是 MIME 类型
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    /**
     * 导出告警文件
     */
    async downAlarmFile() {
      let url = "/export/alarm/order/exportEventInfo";
      // let url = '/export/alarm/order/upload';
      const element = document.querySelector(".down_alarm_file_map_dom");
      console.log(element, "element");
      debugger;
      if (element || this.mapDom) {
        this.fileLoading = true;
        setTimeout(async () => {
          const dom = this.mapDom ? this.mapDom : element;
          const result = await this.htmlElementToBolb(dom);
          if (result.status) {
            this.downFile(result, url);
          }
        }, 10);
      }
    },
    downFile(result, url) {
      const blob = result.blob;
      const fromData = new FormData();
      fromData.append("file", blob);
      fromData.append("warningOrderId", this.orderData.warningOrderId);
      fromData.append("orderStatus", this.orderData.orderStatus);
      fromData.append("exportSource", this.exportSource);
      if (getQueryString("page") === "12") {
        fromData.append("exportType", "2"); // exportType 后端区分转移告警（1）和删除告警（2）
      }
      if (getQueryString("page") === "13") {
        fromData.append("exportType", "1");
      }
      // 修改事发地点的话，计算后的角度horiAzimuthAngle，devicePitch，deviceHorizontal
      if (this.orderData.horiAzimuthAngle) {
        fromData.append("horiAzimuthAngle", this.orderData.horiAzimuthAngle);
      }
      if (this.orderData.devicePitch) {
        fromData.append(
          "devicePitch",
          this.addAngleStr(this.orderData.devicePitch)
        );
      }
      if (this.orderData.deviceHorizontal) {
        fromData.append(
          "deviceHorizontal",
          this.addAngleStr(this.orderData.deviceHorizontal)
        );
      }
      fromData.append("exportView", this.exportView);
      const imgUrl = URL.createObjectURL(blob);
      console.log(imgUrl, "base64Image");
      downLoadZipPost(
        url,
        `${this.formatDateTimeInChinese(this.orderData.alarmTime)} ${
          this.orderData.alarmBody
        }`,
        fromData,
        (status) => {
          this.fileLoading = false;
          status
            ? $message.s("下载告警文件成功")
            : $message.e("下载告警文件失败");
        }
      );
    },
    /**
     * 设置Map dom 容器
     */
    setMapElement() {
      const wrapper = document.querySelector("#mapbox-wrapper");
      wrapper.innerHTML = ""; // 清空存储地图dom的容器
      this.mapDom.classList.add("down_alarm_file_map_dom");
      wrapper.appendChild(this.mapDom);
    },
    /**
     * 将Map dom 移动回原位置
     */
    moveMapDom() {
      const dom = document.querySelector(".down_alarm_file_map_dom");
      if (!dom) {
        return;
      }
      dom.classList.remove(".down_alarm_file_map_dom");
      const wrapper = document.querySelector(
        ".medias-map-component .event-mapol"
      );
      wrapper.appendChild(dom);
    },
    addAngleStr(str) {
      if (str !== null && str !== undefined) {
        // 保留两位小数
        str = Number(str).toFixed(2);
        return str + "°";
      } else {
        return "";
      }
    },
    /**
     * 将日期字符转化为年月日时分秒
     * @param dateString
     * @returns {string}
     */
    formatDateTimeInChinese(dateString) {
      // 解析日期字符串为Date对象
      const date = new Date(dateString);

      // 获取并格式化各个部分
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      // 拼接结果，并添加中文词汇
      return `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
    },
    /**
     * 展示督办详情
     */
    showSupervisionDetail() {
      this.supervisionDetail = true;
    },
    /**
     * 判断租户或者铁塔视角
     * @returns {boolean} true/false 铁塔/租户
     */
    isDisabled() {
      let source = this.$store.getters.userInfo.userType;
      return source === "0";
    },
  },
};
</script>
<style lang="scss" scoped>
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  //padding: 6px 24px;
  color: #22222c;
  height: 48px;
  padding: 0 24px;
}

.btn {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #606266;

  img {
    vertical-align: -1px;
    width: 24px;
  }

  /deep/ .el-button.common-button {
    padding: 0;
    color: #606266;
  }

  &.disabled {
    cursor: not-allowed;
    opacity: 0.4;
  }
  .supervision-btn {
    padding: 6px 12px;
    animation: flicker 1s linear infinite;
    &:hover,
    &:focus {
      color: #f56c6c;
      background: #fef0f0;
      border-color: #fbc4c4;
    }
  }
}

.custom-hr {
  //margin-left: 0px;
  //margin-right: 5px;
  //margin-bottom: 0px;
  margin: 0 24px;
}

.value {
  margin-top: 10px;
}

/deep/ .down-img > span {
  display: flex;
  align-items: center;
}

.down-file {
  display: flex;
  align-items: center;
  ::v-deep span {
    display: flex;
    align-items: center;
  }
}

.fs-14 {
  font-size: 14px;
}

.fs-12 {
  font-size: 12px;
}

.ml-5 {
  margin-left: 6px;
}

.mt-1 {
  margin-top: 1px;
}
.flex-center {
  display: flex;
  align-items: center;
}
.pt-2 {
  padding-top: 2px;
}
@keyframes flicker {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.6;
  }
  100% {
    opacity: 1;
  }
}
</style>
<style lang="scss">
.eventDetailAll {
  overflow-x: hidden;
}
.down_alarm_file_map_dom {
  height: 100%;
  aspect-ratio: 16 / 9;
}
</style>
